<template>
	<div class="system-role">
        <div class="top">
			<Row :gutter="10">
				<Col :span="4">
					<Input v-model="keyWord" placeholder="输入会员卡号/姓名/手机号码" />
				</Col>
				<Col :span="4">
					<Select placeholder="全部患者类型" v-model="customerType">
						<Option v-for="item in diseaseTypeList" :value="item.id" :key="item.value">{{ item.itemValue }}</Option>
					</Select>
				</Col>
				<Col :span="4">
					<Select v-model="selectTags" multiple placeholder="全部患者标签">
						<Option v-for="item in tagList" :value="item.id" :key="item.id">{{ item.tagName }}</Option>
					</Select>
				</Col>
                <Col :span="4">
                    <div>
					    <DatePicker style="width:100%;" type="daterange" v-model="daterange" placement="top-start" placeholder="请选择干预时间范围"></DatePicker>
                    </div>
				</Col>
                <Col :span="4">
                    <div>
                        <Button class="ml20" type="primary" @click="search">查询</Button>
					    <Button class="ml20" type="default" plain @click="reset">清空</Button>
                    </div>
				</Col>
                <Col :span="4" align="right">
					<Button type="primary" @click="updateBatch">批量干预</Button>
                </Col>
			</Row>
		</div>

        <!-- <div class="top">
			<Row :gutter="10" justify="center">
				<Col span="4">
					<Button type="success" icon="md-add" @click="updateBatch">批量干预</Button>
				</Col>
			</Row>
		</div> -->

		<Drawer :title="isBatch?'批量健康干预':'健康干预'" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form class="form" :model="editedItem" :rules="rules">
                <div v-show="isBatch===false"><b>基本信息</b></div>
                <Row :gutter="10" v-show="isBatch===false">
                    <Col :span="12">
                        <FormItem class="formitem" label="姓名" label-position="left">
                            <span>{{editedItem.customerName}}</span>
						</FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="formitem" label="出生日期" label-position="left">
                            <span>{{editedItem.birthday | YMD}}</span>
						</FormItem>
                    </Col>
                </Row>
                <Row :gutter="10"  v-show="isBatch===false">
                    <Col :span="12">
                        <FormItem class="formitem" label="性别" label-position="left">
                            <span v-if="editedItem.sex==1">男</span>
                            <span v-else-if="editedItem.sex==2">女</span>
                            <span v-else>-</span>
						</FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="formitem" label="手机号码" label-position="left">
                            <span>{{editedItem.mobile}}</span>
						</FormItem>
                    </Col>
                </Row>
                <Row :gutter="10"  v-show="isBatch===false">
                    <Col :span="12">
                        <FormItem class="formitem" label="身高(cm)" label-position="left">
                            <span>{{editedItem.height}}</span>
						</FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="formitem" label="体重(kg)" label-position="left">
                            <span>{{editedItem.weight}}</span>
						</FormItem>
                    </Col>
                </Row>
                <Row :gutter="10" v-if="isBatch">
                    <FormItem style="white-space:nowrap;" label="干预患者" label-position="left" :label-width="65">
                        <Select multiple v-model="selection" placeholder="请选择一名或多名患者">
                            <Option
                                class="select"
                                v-for="item in items"
                                :value="item.id"
                                :key="item.id"
                            >{{ item.customerName }}</Option>
                        </Select>
                    </FormItem>
                </Row>
                <Divider />
                <div><b>干预详情</b></div>
                <Row type="flex" :gutter="10">
                    <Col :span="24">
                        <FormItem label="干预类型" label-position="left">
                            <RadioGroup v-model="editedItem.interventionType" @on-change="interventionTypeChange">
                                <Radio v-for="item in typeInterventionList" :key="item.id" :label="item.itemKey">{{item.itemValue}}</Radio>
                            </RadioGroup>
						</FormItem>
					</Col>
                    <Col :span="24">
                        <FormItem label="干预模板" label-position="left">
                            <Select v-model="editedItem.templateId" @on-change="templateIdChange" class="cube" placeholder="请选择干预模板">
								<Option
									class="select"
									v-for="item in templateInterventionList"
									:value="item.id"
									:key="item.id"
								>{{ item.templateName }}</Option>
							</Select>
                        </FormItem>
					</Col>
                    <Col :span="24">
						<FormItem label="干预内容" label-position="left" prop="interventionContent">
							<Input  class="cube" type="textarea" v-model="editedItem.interventionContent" placeholder="" />
						</FormItem>
					</Col>
					<Col :span="24">
                        <FormItem label="发送方式" label-position="left">
                            <RadioGroup v-model="showTimePicker">
                                <Radio :label="false">立即发送</Radio>
                                <Radio :label="true">定时发送</Radio>
                            </RadioGroup>
						</FormItem>
					</Col>
                    <Col :span="24" v-if="showTimePicker">
                        <FormItem label="发送时间" label-position="left">
                            <DatePicker v-model="editedItem.planTime" type="datetime" placeholder="请选择发送时间" />
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" @click="save" :loading="editedIndex===-1?createLoading:updateLoading">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
                    @on-selection-change="tableSelectionchange"
				>
                    <template slot-scope="{ row }" slot="addTime">
                        <span>{{row.addTime | YMDHMS}}</span>
                    </template>

                    <template slot-scope="{ row }" slot="birthday">
                        <span>{{row.birthday | AGE}}</span>
                    </template>

                    <template slot-scope="{ row }" slot="customerType">
                        <span>{{getCustomerType(row)}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="sex">
						<span v-if="Number(row.sex)===1">男</span>
						<span v-else-if="Number(row.sex)===2">女</span>
						<span v-else>-</span>
					</template>
					<template slot-scope="{row}" slot="action">
                        <!-- /customer/detail?id=19 -->
                        <router-link :to="{path: '/customer/detail',query:{id:row.id}}">查看</router-link>
                        <a class="ml10" href="javascript:;" @click="create(row)">干预</a>
						<!-- <Button type="primary" size="small" @click="update(row)">修改</Button> -->
						<!-- <Button class="ml10" type="primary" ghost size="small" @click="remove(row)">删除</Button> -->
					</template>
				</Table>
				<Row class="pagination">
                    <Col align="right"><Page :current="page" :total="totalNum" show-total @on-change="pageChange" /></Col>
				</Row>
			</div>
		</div>
	</div>
</template>
<script>
import { customerPageQueryList } from '@api/customer.js'
import { interventionAdd, interventionBatchAdd, interventionQueryListByType} from '@api/intervention.js'
import { dicGetItemByCode } from '@api/dic.js'
import { mapState } from '@lib/x_.js'
import moment from 'moment'
export default {
	data() {
		return {
            rules: {
				// interventionContent: [{ required: true, message: '请输入干预内容', trigger: 'blur' }, { type: 'string', min: 6, message: '最少6个字符', trigger: ['blur','change'] }]
            },
			showDrawer: false,
			loading: false,
			updateLoading: false,
            createLoading: false,
			editedIndex: -1,
			editedItem: {
                interventionContent: '',
                interventionType: '',
                templateId: '',
                customerId: '',
                planTime: '',
			},
			defaultItem: {
				interventionContent: '',
                interventionType: '',
                templateId: '',
                customerId: '',
                planTime: '',
            },
            showTimePicker: false,
			items: [],
			page: 1,
			pageSize: 10,
            totalNum: 0,
			tableColumns: [
                {
					width: 50,
                    type: 'selection',
                },
                {
					title: '档案编号',
					align: 'left',
					width: 130,
					key: 'customerFileNumber',
				},
				{
					width: 130,
					title: '姓名',
					align: 'left',
					key: 'customerName',
                },
				{
					title: '性别',
					width: 130,
					align: 'left',
					slot: 'sex',
				},
				{
					title: '年龄',
					align: 'left',
					slot: 'birthday',
					width: 130,
				},
				{
					title: '患者类型',
					align: 'left',
					width: 170,
					slot: 'customerType',
				},
				{
					title: '患者标签',
					align: 'left',
					width: 250,
					key: 'tags',
				},
				{
					title: '手机号码',
					align: 'left',
					width: 130,
					key: 'mobile',
				},
				{
					title: '最近干预时间',
					slot: 'addTime',
					align: 'left',
					width: 170
				},
				{
					title: '操作',
					slot: 'action',
					align: 'left',
					width: 150,
                },
                {
					title: ' ',
					key: '',
					align: '',
				}
            ],

            daterange: ["",""],
            customerType: "",
            keyWord: "",
            selectTags: [],

            selection: [],
            isBatch: false,
		}
	},
	mounted() {
        this.customerPageQueryList();
	},
	computed: {
        ...mapState(['diseaseTypeList','familyList','diseaseHistoryList','familyHistoryList','nowTreatmentList','tagList','userList','typeInterventionList','templateInterventionList']),
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
        },
	},
	methods: {
        templateIdChange(id){
            const idx = this.templateInterventionList.findIndex((item,i) => item.id === id)
            if (idx > -1) {
                const { templateType,templateContent } = this.templateInterventionList[idx];
                this.editedItem.interventionContent = templateContent;
                const idx1 = this.typeInterventionList.findIndex((item,i) => item.itemKey === templateType)
                this.editedItem.interventionType = this.typeInterventionList[idx1].itemKey;
            }
        },
        interventionTypeChange(t){
            const idx = this.templateInterventionList.findIndex((item,i) => item.templateType === t)
            if (idx > -1) {
                this.editedItem.templateId = this.templateInterventionList[idx]['id']
                this.editedItem.interventionContent = this.templateInterventionList[idx]['templateContent']
            } else {
                this.editedItem.templateId=""
                this.editedItem.interventionContent = ""
                this.$Message.error("该类型未配置模板")
            }
        },
        getCustomerType(row) {
            const { customerType } = row;
            const { diseaseTypeList } = this;
            const idx = diseaseTypeList.findIndex((item,i) => String(item.itemKey) === customerType)
            if (idx > -1) {
                return diseaseTypeList[idx]['itemValue']
            } else {
                return '-'
            }
        },
        search() {
            this.page = 1;
            this.pageSize = 10;
            this.customerPageQueryList()
        },
        reset() {
            this.page = 1;
            this.pageSize = 10;
            this.customerType= '';
            this.keyWord='';
            this.selectTags= [];
            this.daterange= [];
        },
       
        
        radioChange() {
            console.log("radioChange")
        },
        tableSelectionchange(selection){
            selection.map((item,i) => selection[i] = item.id)
            this.selection = selection
        },
        updateBatch() {
            const { selection } = this;
            if (!selection.length) {
                return this.$Modal.warning({
					title: '批量干预',
					content: '请先选择患者'
				})
            }
            this.create();
            this.isBatch = true;
        },
		pageChange(page) {
			this.page = page
			this.customerPageQueryList()
		},
		update(item) {
            const { id } = item;
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true
        },
		create(row) {
            this.editedIndex = -1
            if (row) {
                this.editedItem = Object.assign({}, row)
                this.isBatch = false;
            } else {
			    this.editedItem = Object.assign({}, this.defaultItem)
            }
			this.showDrawer = true
		},
		remove(item, idx) {
			//done this.close();
		},
		async save() {
            if (this.isBatch) {
                const { selection } = this;
                let { interventionContent,templateId,interventionType,planTime } = this.editedItem;
                if (planTime) {
                    planTime = moment(planTime).format('YYYY-MM-DD HH:mm:ss')
                }
				this.createLoading || (this.createLoading = true)
                const res = await interventionBatchAdd({
                    customerIds: selection,
                    interventionContent,
                    templateId,
                    interventionType,
                    planTime,
                })
                this.createLoading = false;
                this.modal(res,'批量干预')
                this.close()
                return 
                
            }
			if (this.editedIndex > -1) {
                const { id,interventionContent,templateId,interventionType,planTime	} = this.editedItem
                if (!interventionContent) {
                    return this.$Message.error("请输入干预内容")
                }
				this.updateLoading || (this.updateLoading = true)
				const res = await interventionAdd({ customerId: id,interventionContent,templateId,interventionType,planTime	})
				this.updateLoading = false
				this.modal(res)
			} else {
                let { id,interventionContent,templateId,interventionType,planTime } = this.editedItem
                if (planTime) {
                    planTime = moment(planTime).format('YYYY-MM-DD HH:mm:ss')
                }
				this.createLoading || (this.createLoading = true)
				const res = await interventionAdd({ customerId: id,interventionContent,templateId,interventionType,planTime	})
				this.createLoading = false
				this.modal(res)
			}
			this.customerPageQueryList()
			this.close()
		},
		modal(res,title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
				})
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg
				})
			}
		},
		close() {
            this.showDrawer = false
            this.isBatch = false
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
        customerPageQueryList() {
            const { selectTags, customerType,keyWord,tagList,daterange, page, pageSize, loading } = this;
            console.log("daterange1》", daterange)
            const [beginTime, endTime] = daterange;
            console.log("daterange2》", daterange)
            const obj = {tagList: selectTags, beginTime,endTime, customerType,keyWord,page,pageSize  }
            if (beginTime) {
                obj.beginTime = moment(beginTime).format('YYYY-MM-DD HH:mm:ss')
            }
            if (endTime) {
                obj.endTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss')
            }
            this.loading || (this.loading = true)
			customerPageQueryList(obj)
				.then(res => {
					this.loading = false
					if (res.code === '0') {
                        const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data;
                        this.items = items;
                        this.page = currentPage;
                        this.totalNum = totalNum;
						console.log('this.items->', this.items)
					} else {
                        this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					    })
                    }
				})
				.catch(err => {
					this.loading = false
				})
		},
		// customerPageQueryList() {
		// 	const { page, pageSize, loading } = this
		// 	if (loading) return
		// 	this.loading = true
		// 	customerPageQueryList({
		// 		page,
		// 		pageSize
		// 	})
		// 		.then(res => {
		// 			this.loading = false
		// 			if (res.code === '0') {
		// 				const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
		// 				;(this.items = items), (this.page = currentPage), (this.totalNum = totalNum)
		// 			}
		// 		})
		// 		.catch(err => {
		// 			this.loading = false
		// 		})
		// }
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped>
.formitem{
    margin-bottom: 0;
}
.cube{
    max-width: 500px;
}
.label-group {
	display: block;
}
.system-role {
	background-color: #fff;
}
.label {
    min-width: 60px;
    margin-right: 10px;
    display: inline-block;
    vertical-align: middle;
    white-space: nowrap;
    overflow: hidden;
}
</style>